package com.magpiebridge.controller;

import com.magpiebridge.pojo.Manager;
import com.magpiebridge.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@CrossOrigin
@RestController
public class ManagerController {
    @Autowired
    private ManagerService managerService;

    @GetMapping("/getAllManager")
    public List<Manager> getAllManager(){
        return managerService.getAllManager();
    }

    @GetMapping("/getManagerById/{id}")
    public Manager getManagerById(@PathVariable Integer id){
        return managerService.getManagerById(id);
    }

    @PostMapping("/insertManager")
    public String insertManager(@RequestBody Manager manager){
        String admin = manager.getAdmin();
        String password = manager.getPassword();
        int result = managerService.insertManager(manager);
        if (result > 0){
            return "注册成功";
        } else {
            return "注册失败";
        }
    }

    @DeleteMapping("/deleteManager/{id}")
    public  String deleteManager(@PathVariable  Integer  id)  {
        try  {
            //  查询管理员是否存在
            Manager  manager  =  managerService.getManagerById(id);
            if  (manager  ==  null)  {
                return  "管理员不存在";
            }
            //  删除管理员
            int  result  =  managerService.deleteManager(id);
            if  (result  >  0)  {
                //  更新数据库状态
                return  "删除成功";
            }  else  {
                return  "删除失败";
            }
        }  catch  (Exception  e)  {
            //  记录日志或警告
            //  TODO:  Log  deletion  information
            // 打印错误信息
            System.err.println(e.getMessage());
            return "系统错误";
        }
    }

    @PostMapping("/updateManager/{id}")
    public String updateManager(@PathVariable Integer id, @RequestBody Manager newManager) {
        try {
            // 查询管理员是否存在
            Manager manager = managerService.getManagerById(id);
            if (manager == null) {
                return "管理员不存在";
            }
            // 更新用户信息
            manager.setId(newManager.getId());
            manager.setAdmin(newManager.getAdmin());
            manager.setPassword(newManager.getPassword());
            int result = managerService.updateManager(manager);
            if (result > 0) {
                return "管理员信息更新成功";
            } else {
                return "管理员信息更新失败";
            }
        } catch (Exception e) {
            // 记录日志或警告
            // TODO: Log update information
            // 打印错误信息
            System.err.println(e.getMessage());
            return "系统错误";
        }
    }

}
